package com.wemei.auto

import com.wemei.auto.api.core.ApiHelper
import com.wemei.auto.api.core.ResultBean
import com.wemei.auto.ui.helper.mohsi.MoshiUtils
import com.wemei.auto.ui.utils.Logger
import com.wemei.auto.ui.utils.PATTERN_YYYY_MM_DD_HH_MM_SS
import com.wemei.auto.ui.utils.SPUtils
import kotlinx.coroutines.CoroutineScope
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.POST
import retrofit2.http.Query
import java.text.SimpleDateFormat
import java.util.Date

val API_SERVICE: ApiService by lazy {
    ApiHelper.create(ApiService::class.java, {
        baseUrl(BuildConfig.BASE_URL)
    }, {
        if (Logger.isDebug) {
            val httpLoggingInterceptor = ApiHelper.getHttpLoggingInterceptor()
            addInterceptor(httpLoggingInterceptor)
        }
        addInterceptor(ConvertInterceptor())
    })
}
val CoroutineScope.api get() = API_SERVICE
fun checkExpiration(): Boolean {
    val userInfoStr = SPUtils.getString("userInfo")
    if (userInfoStr.isBlank()) {
        return true
    }
    val expirationDate = MoshiUtils.parseObject(userInfoStr, UserBean::class.java)?.expirationDate ?: return true
    return SimpleDateFormat(PATTERN_YYYY_MM_DD_HH_MM_SS).parse(expirationDate).before(Date())
}

interface ApiService {

    @GET("/app-api/auto/version/get/version")
    suspend fun version(
        @Query("versionName") versionName: String,
        @Query("buildType") buildType: String,
        @Header("tenant-id") tenantId: String = "172",
        @Header("client-id") clientId: String = "qlsz-auto",
    ): ResultBean<AppVersion?>

    @GET("/app-api/system/dict-data/type")
    suspend fun getDictDataListByType(
        @Query("type") type: String?,
        @Header("tenant-id") tenantId: String = "172",
        @Header("client-id") clientId: String = "qlsz-auto",
    ): ResultBean<MutableList<AppDictDataRespVO>?>

    @POST("/admin-api/system/auth/login")
    suspend fun authLogin(
        @Body body: Any,
        @Header("tenant-id") tenantId: String = "172",
        @Header("client-id") clientId: String = "qlsz-auto",
    ): ResultBean<AccessTokenBean?>

    @GET("/admin-api/system/oauth2/user/get")
    suspend fun userGet(
        @Header("Authorization") authorization: String,
        @Header("tenant-id") tenantId: String = "172",
        @Header("client-id") clientId: String = "qlsz-auto",
    ): ResultBean<UserBean?>
}